<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传图片</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../layui/css/layui.css" media="all">
    <script src="../js/jquery-3.1.0.min.js"></script>
    <script src="../layui/layui.js" charset="utf-8"></script>

    <style>
        .layui-input {
            width: 300px;
        }
    </style>
</head>
<body>
<div class="layui-upload layui-form-item">
    <button class="layui-btn layui-btn-primary layui-btn-sm" id="uploadimg"><i class="layui-icon"></i>选择图片</button>
    <div class="layui-inline layui-word-aux" style="margin-left: 10px">
        图片大小不能超过 1 M
    </div>
    <div class="layui-upload-list" >
        <img class="layui-upload-img" id="img" style="width: 410px;height: 300px">
        <p id="demoText"></p>
    </div>
</div>
<form class="layui-form" action="">
    <div class="layui-form-item">
        <label class="layui-form-label">图片用途：</label>
        <div class="layui-input-inline">
            <select name="imguse" id="imguse" lay-filter="imguse" lay-verify="select" lay-search="">
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">图片公告：</label>
        <div class="layui-input-block">
            <input type="text" name="imgnotice" id="imgnotice" placeholder="图片下方的通知" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">图片链接：</label>
        <div class="layui-input-block">
            <input type="text" name="imghref" id="imghref" placeholder="图片跳转的地址" autocomplete="off" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">图片地址：</label>
        <div class="layui-input-block">
            <input type="text" name="imgurl" id="imgurl" placeholder="图片访问地址,上传图片后自动生成" autocomplete="off"
                   class="layui-input" readonly>
        </div>
    </div>



    <div class="layui-form-item">
        <div class="layui-input-block">
            <button type="submit" class="layui-btn" lay-submit="" lay-filter="addimage">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>
</body>

<script>
    layui.use(['form', 'layedit', 'laydate', 'upload'], function () {
        var form = layui.form
            , layer = layui.layer
            , $ = layui.jquery
            , upload = layui.upload;

        //加载用途（可回收种类）下拉框
        $.ajax({
            type: "get",
            dataType: "json",
            url: "/refuse-web/api/indeximg/imguselist",
            async: true,
            success: function (data) {
                var res = data.data
                if (res != undefined && res != null && res != "") {
                    var html = "";
                    html += "<option value='' >请选择</option>";
                    for (var i = 0; i < res.length; i++) {
                        html += "<option value=" + res[i] + ">" + res[i] + "</option>";
                    }
                    $("#imguse").append(html);
                }
                //重新渲染select
                form.render('select');
            },
            error: function (msg) {
                alert("服务器请求失败！");
            }
        });

        //普通图片上传
        var uploadInst = upload.render({
            elem: '#uploadimg'
            , url: '/refuse-web/api/indeximg/upload/'
            , size: 1024 //限制文件大小，单位 KB
            , before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#img').attr('src', result); //图片链接（base64）
                });
            }
            , done: function (res) {
                //上传成功
                if (res.code == 0) {
                    console.log(res.data);
                    $("#imgurl").val(res.data);
                    return layer.msg("上传成功");
                } else {
                    return layer.msg('上传失败');
                }
            }
            , error: function () {
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
        });

        //监听提交
        form.on('submit(addimage)', function (data) {
            var imguse = $("#imguse").val();
            var imgurl = $("#imgurl").val();
            var imgnotice = $("#imgnotice").val();
            var imghref = $("#imghref").val();
            //封装对象
            var image = {
                imguse: imguse,
                imgurl: imgurl,
                imgnotice: imgnotice,
                imghref: imghref
            }
            $.ajax({
                url: '/refuse-web/api/indeximg/addimg',
                method: 'post',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(image),//将对象转换成json字符串
                dataType: 'JSON',
                success:
                    function (res) {
                        if (res.code = '0') {
                            layer.msg(res.msg);
                        } else {
                            layer.msg(res.msg);
                        }
                    }
                ,
                error: function (data) {
                    layer.msg("服务器忙...")
                }
            })
            ;
        })
        return false;
    });
</script>
</html>